package server.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import server.demo.dto.OrderDTO;
import server.demo.dto.TicketDTO;
import server.demo.dto.TicketPurchaseRequest;
import server.demo.dto.TransferTicketPurchaseRequest;
import server.demo.dto.ticket.RefundTicketRequest;
import server.demo.dto.ticket.RescheduleTicketRequest;
import server.demo.entity.*;
import server.demo.repository.*;
import server.demo.entity.Payment;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class TicketService {
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private TicketRepository ticketRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private TrainRepository trainRepository;
    
    @Autowired
    private SeatRepository seatRepository;
    
    @Autowired
    private StationRepository stationRepository;
    
    @Autowired
    private PaymentRepository paymentRepository;
    
    public OrderDTO purchaseTickets(TicketPurchaseRequest request) {
        // 验证用户
        Optional<User> user = userRepository.findById(request.getUserId());
        if (user.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证座位可用性
        for (TicketPurchaseRequest.TicketInfo ticketInfo : request.getTickets()) {
            if (!isSeatAvailable(ticketInfo.getSeatId())) {
                throw new RuntimeException("座位 " + ticketInfo.getSeatId() + " 已被占用");
            }
        }
        
        // 创建订单
        Order order = new Order();
        order.setOrderNumber(generateOrderNumber());
        order.setUser(user.get());
        order.setOrderStatus(Order.OrderStatus.PENDING);
        order.setOrderType(Order.OrderType.DIRECT); // 简化处理，默认直达
        
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<Ticket> tickets = new ArrayList<>();
        
        // 创建票务
        for (TicketPurchaseRequest.TicketInfo ticketInfo : request.getTickets()) {
            Ticket ticket = createTicket(order, ticketInfo);
            tickets.add(ticket);
            totalAmount = totalAmount.add(ticket.getTicketPrice());
            
            // 标记座位为不可用
            Seat seat = ticket.getSeat();
            seat.setIsAvailable(false);
            seatRepository.save(seat);
        }
        
        order.setTotalAmount(totalAmount);
        Order savedOrder = orderRepository.save(order);
        
        // 保存票务
        for (Ticket ticket : tickets) {
            ticket.setOrder(savedOrder);
            ticketRepository.save(ticket);
        }
        
        // 返回订单信息
        OrderDTO orderDTO = new OrderDTO(savedOrder);
        List<TicketDTO> ticketDTOs = tickets.stream()
                .map(TicketDTO::new)
                .collect(Collectors.toList());
        orderDTO.setTickets(ticketDTOs);
        
        return orderDTO;
    }
    
    private boolean isSeatAvailable(Long seatId) {
        Optional<Seat> seat = seatRepository.findById(seatId);
        if (seat.isEmpty()) {
            return false;
        }
        
        // 检查座位是否可用且没有被占用的票务
        return seat.get().getIsAvailable() && 
               ticketRepository.countOccupiedBySeatId(seatId) == 0;
    }
    
    private Ticket createTicket(Order order, TicketPurchaseRequest.TicketInfo ticketInfo) {
        // 获取相关实体
        Train train = trainRepository.findById(ticketInfo.getTrainId())
                .orElseThrow(() -> new RuntimeException("车次不存在"));
        
        Seat seat = seatRepository.findById(ticketInfo.getSeatId())
                .orElseThrow(() -> new RuntimeException("座位不存在"));
        
        Station startStation = stationRepository.findById(ticketInfo.getStartStationId())
                .orElseThrow(() -> new RuntimeException("起始站不存在"));
        
        Station endStation = stationRepository.findById(ticketInfo.getEndStationId())
                .orElseThrow(() -> new RuntimeException("终点站不存在"));
        
        // 构建出发和到达时间
        LocalDateTime departureDateTime = LocalDateTime.of(train.getTravelDate(), train.getDepartureTime());
        LocalDateTime arrivalDateTime = LocalDateTime.of(train.getTravelDate(), train.getArrivalTime());
        
        // 如果到达时间早于出发时间，说明是跨日
        if (arrivalDateTime.isBefore(departureDateTime)) {
            arrivalDateTime = arrivalDateTime.plusDays(1);
        }
        
        // 创建票务
        Ticket ticket = new Ticket();
        ticket.setOrder(order);
        ticket.setTrain(train);
        ticket.setSeat(seat);
        ticket.setPassengerName(ticketInfo.getPassengerName());
        ticket.setPassengerIdCard(ticketInfo.getPassengerIdCard());
        ticket.setStartStation(startStation);
        ticket.setEndStation(endStation);
        ticket.setDepartureTime(departureDateTime);
        ticket.setArrivalTime(arrivalDateTime);
        ticket.setTicketPrice(seat.getPrice());
        ticket.setTicketStatus(Ticket.TicketStatus.VALID);
        
        return ticket;
    }
    
    private String generateOrderNumber() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int)(Math.random() * 9000) + 1000);
        return "ORD" + timestamp + random;
    }
    
    public List<OrderDTO> getAllOrders() {
        List<Order> orders = orderRepository.findAll();
        return orders.stream()
                .map(order -> {
                    OrderDTO dto = new OrderDTO(order);
                    List<TicketDTO> tickets = ticketRepository.findByOrderId(order.getId())
                            .stream()
                            .map(TicketDTO::new)
                            .collect(Collectors.toList());
                    dto.setTickets(tickets);
                    return dto;
                })
                .collect(Collectors.toList());
    }
    
    public List<OrderDTO> getOrdersByUserId(Long userId) {
        List<Order> orders = orderRepository.findByUserIdOrderByCreatedAtDesc(userId);
        return orders.stream()
                .map(order -> {
                    OrderDTO dto = new OrderDTO(order);
                    List<TicketDTO> tickets = ticketRepository.findByOrderId(order.getId())
                            .stream()
                            .map(TicketDTO::new)
                            .collect(Collectors.toList());
                    dto.setTickets(tickets);
                    return dto;
                })
                .collect(Collectors.toList());
    }
    
    public Optional<OrderDTO> getOrderById(Long orderId) {
        return orderRepository.findById(orderId)
                .map(order -> {
                    OrderDTO dto = new OrderDTO(order);
                    List<TicketDTO> tickets = ticketRepository.findByOrderId(order.getId())
                            .stream()
                            .map(TicketDTO::new)
                            .collect(Collectors.toList());
                    dto.setTickets(tickets);
                    return dto;
                });
    }
    
    public List<TicketDTO> getTicketsByUserId(Long userId) {
        return ticketRepository.findByOrderUserIdOrderByCreatedAtDesc(userId)
                .stream()
                .map(TicketDTO::new)
                .collect(Collectors.toList());
    }
    
    public void cancelOrder(Long orderId) {
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (orderOpt.isEmpty()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        if (order.getOrderStatus() != Order.OrderStatus.PENDING) {
            throw new RuntimeException("只能取消待付款的订单");
        }
        
        // 取消订单
        order.setOrderStatus(Order.OrderStatus.CANCELLED);
        orderRepository.save(order);
        
        // 取消相关票务并释放座位
        List<Ticket> tickets = ticketRepository.findByOrderId(orderId);
        for (Ticket ticket : tickets) {
            ticket.setTicketStatus(Ticket.TicketStatus.CANCELLED);
            ticketRepository.save(ticket);
            
            // 释放座位
            Seat seat = ticket.getSeat();
            seat.setIsAvailable(true);
            seatRepository.save(seat);
        }
    }
    
    public void deleteOrder(Long orderId) {
        Optional<Order> orderOpt = orderRepository.findById(orderId);
        if (orderOpt.isEmpty()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        // 只允许删除已取消或已退票的订单
        if (order.getOrderStatus() != Order.OrderStatus.CANCELLED && 
            order.getOrderStatus() != Order.OrderStatus.REFUNDED) {
            throw new RuntimeException("只能删除已取消或已退票的订单");
        }
        
        // 删除相关票务
        List<Ticket> tickets = ticketRepository.findByOrderId(orderId);
        for (Ticket ticket : tickets) {
            ticketRepository.delete(ticket);
        }
        
        // 删除相关支付记录
        List<Payment> payments = paymentRepository.findByOrderId(orderId);
        for (Payment payment : payments) {
            paymentRepository.delete(payment);
        }
        
        // 删除订单
        orderRepository.delete(order);
    }
    
    /**
     * 退票
     */
    public void refundTicket(RefundTicketRequest request) {
        Optional<Order> orderOpt = orderRepository.findById(request.getOrderId());
        if (orderOpt.isEmpty()) {
            throw new RuntimeException("订单不存在");
        }
        
        Order order = orderOpt.get();
        if (order.getOrderStatus() == Order.OrderStatus.CANCELLED) {
            throw new RuntimeException("订单已取消，无法退票");
        }
        
        if (order.getOrderStatus() == Order.OrderStatus.REFUNDED) {
            throw new RuntimeException("订单已退票");
        }
        
        // 检查是否允许退票（这里简化处理，实际应该检查出发时间等）
        List<Ticket> tickets = ticketRepository.findByOrderId(request.getOrderId());
        for (Ticket ticket : tickets) {
            if (ticket.getDepartureTime().isBefore(LocalDateTime.now())) {
                throw new RuntimeException("已出发的票务无法退票");
            }
        }
        
        // 执行退票
        order.setOrderStatus(Order.OrderStatus.REFUNDED);
        orderRepository.save(order);
        
        // 更新票务状态并释放座位
        for (Ticket ticket : tickets) {
            ticket.setTicketStatus(Ticket.TicketStatus.REFUNDED);
            ticketRepository.save(ticket);
            
            // 释放座位
            Seat seat = ticket.getSeat();
            seat.setIsAvailable(true);
            seatRepository.save(seat);
        }
    }
    
    /**
     * 改签
     */
    public OrderDTO rescheduleTicket(RescheduleTicketRequest request) {
        // 验证原订单
        Optional<Order> originalOrderOpt = orderRepository.findById(request.getOriginalOrderId());
        if (originalOrderOpt.isEmpty()) {
            throw new RuntimeException("原订单不存在");
        }
        
        Order originalOrder = originalOrderOpt.get();
        if (originalOrder.getOrderStatus() == Order.OrderStatus.CANCELLED) {
            throw new RuntimeException("订单已取消，无法改签");
        }
        
        if (originalOrder.getOrderStatus() == Order.OrderStatus.REFUNDED) {
            throw new RuntimeException("订单已退票，无法改签");
        }
        
        // 检查原票务是否允许改签
        List<Ticket> originalTickets = ticketRepository.findByOrderId(request.getOriginalOrderId());
        for (Ticket ticket : originalTickets) {
            if (ticket.getDepartureTime().isBefore(LocalDateTime.now().plusHours(2))) {
                throw new RuntimeException("发车前2小时内无法改签");
            }
        }
        
        // 验证新座位可用性
        if (!isSeatAvailable(request.getNewSeatId())) {
            throw new RuntimeException("新座位不可用");
        }
        
        // 获取新的相关实体
        Train newTrain = trainRepository.findById(request.getNewTrainId())
                .orElseThrow(() -> new RuntimeException("新车次不存在"));
        
        Seat newSeat = seatRepository.findById(request.getNewSeatId())
                .orElseThrow(() -> new RuntimeException("新座位不存在"));
        
        // 取消原订单
        originalOrder.setOrderStatus(Order.OrderStatus.CANCELLED);
        orderRepository.save(originalOrder);
        
        // 取消原票务并释放座位
        for (Ticket ticket : originalTickets) {
            ticket.setTicketStatus(Ticket.TicketStatus.CANCELLED);
            ticketRepository.save(ticket);
            
            Seat originalSeat = ticket.getSeat();
            originalSeat.setIsAvailable(true);
            seatRepository.save(originalSeat);
        }
        
        // 创建新订单
        Order newOrder = new Order();
        newOrder.setOrderNumber(generateOrderNumber());
        newOrder.setUser(originalOrder.getUser());
        newOrder.setOrderStatus(Order.OrderStatus.CONFIRMED); // 改签订单直接确认
        newOrder.setOrderType(Order.OrderType.RESCHEDULE);
        newOrder.setTotalAmount(newSeat.getPrice());
        Order savedNewOrder = orderRepository.save(newOrder);
        
        // 创建新票务（简化处理，只处理一张票）
        Ticket originalTicket = originalTickets.get(0);
        Ticket newTicket = new Ticket();
        newTicket.setOrder(savedNewOrder);
        newTicket.setTrain(newTrain);
        newTicket.setSeat(newSeat);
        newTicket.setPassengerName(originalTicket.getPassengerName());
        newTicket.setPassengerIdCard(originalTicket.getPassengerIdCard());
        newTicket.setStartStation(originalTicket.getStartStation());
        newTicket.setEndStation(originalTicket.getEndStation());
        
        // 设置新的时间
        LocalDateTime newDepartureDateTime = LocalDateTime.of(
            LocalDateTime.parse(request.getTravelDate() + "T00:00:00").toLocalDate(),
            newTrain.getDepartureTime()
        );
        LocalDateTime newArrivalDateTime = LocalDateTime.of(
            LocalDateTime.parse(request.getTravelDate() + "T00:00:00").toLocalDate(),
            newTrain.getArrivalTime()
        );
        
        if (newArrivalDateTime.isBefore(newDepartureDateTime)) {
            newArrivalDateTime = newArrivalDateTime.plusDays(1);
        }
        
        newTicket.setDepartureTime(newDepartureDateTime);
        newTicket.setArrivalTime(newArrivalDateTime);
        newTicket.setTicketPrice(newSeat.getPrice());
        newTicket.setTicketStatus(Ticket.TicketStatus.VALID);
        
        ticketRepository.save(newTicket);
        
        // 标记新座位为不可用
        newSeat.setIsAvailable(false);
        seatRepository.save(newSeat);
        
        // 返回新订单信息
        OrderDTO newOrderDTO = new OrderDTO(savedNewOrder);
        List<TicketDTO> ticketDTOs = List.of(new TicketDTO(newTicket));
        newOrderDTO.setTickets(ticketDTOs);
        
        return newOrderDTO;
    }
    
    // ========== 管理员票务管理方法 ==========
    
    /**
     * 获取所有票务（支持搜索）
     */
    public List<TicketDTO> getAllTickets(String trainNumber, String passengerName, String status) {
        List<Ticket> tickets = ticketRepository.findAll();
        
        // 应用过滤条件
        if (trainNumber != null && !trainNumber.trim().isEmpty()) {
            tickets = tickets.stream()
                    .filter(ticket -> ticket.getTrain().getTrainNumber().contains(trainNumber.trim()))
                    .collect(Collectors.toList());
        }
        
        if (passengerName != null && !passengerName.trim().isEmpty()) {
            tickets = tickets.stream()
                    .filter(ticket -> ticket.getPassengerName().contains(passengerName.trim()))
                    .collect(Collectors.toList());
        }
        
        if (status != null && !status.trim().isEmpty()) {
            try {
                Ticket.TicketStatus ticketStatus = Ticket.TicketStatus.valueOf(status.trim());
                tickets = tickets.stream()
                        .filter(ticket -> ticket.getTicketStatus() == ticketStatus)
                        .collect(Collectors.toList());
            } catch (IllegalArgumentException ignored) {
                // 无效状态，忽略过滤
            }
        }
        
        return tickets.stream()
                .map(TicketDTO::new)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据ID获取票务详情
     */
    public Optional<TicketDTO> getTicketById(Long ticketId) {
        return ticketRepository.findById(ticketId)
                .map(TicketDTO::new);
    }
    
    /**
     * 取消单张票务
     */
    public void cancelTicket(Long ticketId) {
        Optional<Ticket> ticketOpt = ticketRepository.findById(ticketId);
        if (ticketOpt.isEmpty()) {
            throw new RuntimeException("票务不存在");
        }
        
        Ticket ticket = ticketOpt.get();
        
        if (ticket.getTicketStatus() == Ticket.TicketStatus.CANCELLED) {
            throw new RuntimeException("票务已取消");
        }
        
        if (ticket.getTicketStatus() == Ticket.TicketStatus.REFUNDED) {
            throw new RuntimeException("票务已退款");
        }
        
        if (ticket.getTicketStatus() == Ticket.TicketStatus.USED) {
            throw new RuntimeException("票务已使用，无法取消");
        }
        
        // 取消票务
        ticket.setTicketStatus(Ticket.TicketStatus.CANCELLED);
        ticketRepository.save(ticket);
        
        // 释放座位
        Seat seat = ticket.getSeat();
        seat.setIsAvailable(true);
        seatRepository.save(seat);
        
        // 检查订单是否需要更新状态
        Order order = ticket.getOrder();
        List<Ticket> orderTickets = ticketRepository.findByOrderId(order.getId());
        boolean allCancelled = orderTickets.stream()
                .allMatch(t -> t.getTicketStatus() == Ticket.TicketStatus.CANCELLED || 
                              t.getTicketStatus() == Ticket.TicketStatus.REFUNDED);
        
        if (allCancelled && order.getOrderStatus() != Order.OrderStatus.CANCELLED) {
            order.setOrderStatus(Order.OrderStatus.CANCELLED);
            orderRepository.save(order);
        }
    }
    
    /**
     * 删除票务（硬删除）
     */
    public void deleteTicket(Long ticketId) {
        Optional<Ticket> ticketOpt = ticketRepository.findById(ticketId);
        if (ticketOpt.isEmpty()) {
            throw new RuntimeException("票务不存在");
        }
        
        Ticket ticket = ticketOpt.get();
        
        // 释放座位（如果票务状态不是已取消或已退款）
        if (ticket.getTicketStatus() == Ticket.TicketStatus.VALID) {
            Seat seat = ticket.getSeat();
            seat.setIsAvailable(true);
            seatRepository.save(seat);
        }
        
        // 删除票务记录
        ticketRepository.delete(ticket);
        
        // 检查订单是否还有其他票务，如果没有则删除订单
        Order order = ticket.getOrder();
        List<Ticket> remainingTickets = ticketRepository.findByOrderId(order.getId());
        if (remainingTickets.isEmpty()) {
            // 先删除相关的支付记录
            List<Payment> payments = paymentRepository.findByOrderId(order.getId());
            if (!payments.isEmpty()) {
                paymentRepository.deleteAll(payments);
            }
            
            // 再删除订单
            orderRepository.delete(order);
        }
    }
    
    /**
     * 购买换乘票务
     */
    public OrderDTO purchaseTransferTickets(TransferTicketPurchaseRequest request) {
        // 验证用户
        Optional<User> user = userRepository.findById(request.getUserId());
        if (user.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证座位可用性
        for (TransferTicketPurchaseRequest.TransferTicketInfo transferTicketInfo : request.getTransferTickets()) {
            if (!isSeatAvailable(transferTicketInfo.getFirstSeatId())) {
                throw new RuntimeException("第一段座位 " + transferTicketInfo.getFirstSeatId() + " 已被占用");
            }
            if (!isSeatAvailable(transferTicketInfo.getSecondSeatId())) {
                throw new RuntimeException("第二段座位 " + transferTicketInfo.getSecondSeatId() + " 已被占用");
            }
        }
        
        // 创建订单
        Order order = new Order();
        order.setOrderNumber(generateOrderNumber());
        order.setUser(user.get());
        order.setOrderStatus(Order.OrderStatus.PENDING);
        order.setOrderType(Order.OrderType.TRANSFER); // 换乘类型
        
        BigDecimal totalAmount = BigDecimal.ZERO;
        List<Ticket> tickets = new ArrayList<>();
        
        // 创建换乘票务
        for (TransferTicketPurchaseRequest.TransferTicketInfo transferTicketInfo : request.getTransferTickets()) {
            // 创建第一段票务
            Ticket firstTicket = createTransferTicket(order, transferTicketInfo, true);
            tickets.add(firstTicket);
            totalAmount = totalAmount.add(firstTicket.getTicketPrice());
            
            // 标记第一段座位为不可用
            Seat firstSeat = firstTicket.getSeat();
            firstSeat.setIsAvailable(false);
            seatRepository.save(firstSeat);
            
            // 创建第二段票务
            Ticket secondTicket = createTransferTicket(order, transferTicketInfo, false);
            tickets.add(secondTicket);
            totalAmount = totalAmount.add(secondTicket.getTicketPrice());
            
            // 标记第二段座位为不可用
            Seat secondSeat = secondTicket.getSeat();
            secondSeat.setIsAvailable(false);
            seatRepository.save(secondSeat);
        }
        
        order.setTotalAmount(totalAmount);
        Order savedOrder = orderRepository.save(order);
        
        // 保存票务
        for (Ticket ticket : tickets) {
            ticket.setOrder(savedOrder);
            ticketRepository.save(ticket);
        }
        
        // 返回订单信息
        OrderDTO orderDTO = new OrderDTO(savedOrder);
        List<TicketDTO> ticketDTOs = tickets.stream()
                .map(TicketDTO::new)
                .collect(Collectors.toList());
        orderDTO.setTickets(ticketDTOs);
        
        return orderDTO;
    }
    
    /**
     * 创建换乘票务
     */
    private Ticket createTransferTicket(Order order, TransferTicketPurchaseRequest.TransferTicketInfo transferTicketInfo, boolean isFirstSegment) {
        // 根据是第一段还是第二段获取相应的车次和座位
        Long trainId = isFirstSegment ? transferTicketInfo.getFirstTrainId() : transferTicketInfo.getSecondTrainId();
        Long seatId = isFirstSegment ? transferTicketInfo.getFirstSeatId() : transferTicketInfo.getSecondSeatId();
        
        // 获取相关实体
        Train train = trainRepository.findById(trainId)
                .orElseThrow(() -> new RuntimeException((isFirstSegment ? "第一段" : "第二段") + "车次不存在"));
        
        Seat seat = seatRepository.findById(seatId)
                .orElseThrow(() -> new RuntimeException((isFirstSegment ? "第一段" : "第二段") + "座位不存在"));
        
        // 根据是第一段还是第二段确定起始站和终点站
        Station startStation, endStation;
        if (isFirstSegment) {
            // 第一段：原始起点 -> 中转站
            startStation = stationRepository.findById(transferTicketInfo.getStartStationId())
                    .orElseThrow(() -> new RuntimeException("起始站不存在"));
            endStation = stationRepository.findById(transferTicketInfo.getTransferStationId())
                    .orElseThrow(() -> new RuntimeException("中转站不存在"));
        } else {
            // 第二段：中转站 -> 最终终点
            startStation = stationRepository.findById(transferTicketInfo.getTransferStationId())
                    .orElseThrow(() -> new RuntimeException("中转站不存在"));
            endStation = stationRepository.findById(transferTicketInfo.getEndStationId())
                    .orElseThrow(() -> new RuntimeException("终点站不存在"));
        }
        
        // 构建出发和到达时间
        LocalDateTime departureDateTime = LocalDateTime.of(train.getTravelDate(), train.getDepartureTime());
        LocalDateTime arrivalDateTime = LocalDateTime.of(train.getTravelDate(), train.getArrivalTime());
        
        // 如果到达时间早于出发时间，说明是跨日
        if (arrivalDateTime.isBefore(departureDateTime)) {
            arrivalDateTime = arrivalDateTime.plusDays(1);
        }
        
        // 创建票务
        Ticket ticket = new Ticket();
        ticket.setOrder(order);
        ticket.setTrain(train);
        ticket.setSeat(seat);
        ticket.setPassengerName(transferTicketInfo.getPassengerName());
        ticket.setPassengerIdCard(transferTicketInfo.getPassengerIdCard());
        ticket.setStartStation(startStation);
        ticket.setEndStation(endStation);
        ticket.setDepartureTime(departureDateTime);
        ticket.setArrivalTime(arrivalDateTime);
        ticket.setTicketPrice(seat.getPrice());
        ticket.setTicketStatus(Ticket.TicketStatus.VALID);
        
        return ticket;
    }
}